<template>
  <a-modal
    v-model:visible="showComputed"
    width="888px"
    title="Revival"
    wrap-class-name="primary-modal"
    ok-text="Save"
    :destroyOnClose="true"
    @cancel="showComputed = false"
  >
    <a-form ref="fromRef" :model="revivalRequest" layout="vertical" :rules="rules">
      <a-form-item label="Sales Support" name="ssid">
        <a-select ref="select" v-model:value="revivalRequest.ssid" style="width: 120px">
          <a-select-option v-for="ss in salesSupporters" :key="ss.id" :value="ss.id">
            {{ ss.displayName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="Reason" name="reason">
        <a-textarea v-model:value="revivalRequest.reason" :rows="5" />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button key="back" @click="showComputed = false">Cancel</a-button>
      <a-button key="submit" type="primary" :loading="revivalButtonLoading" @click="handleRevival"> Save </a-button>
    </template>
  </a-modal>
</template>

<script setup>
import { reactive, ref, computed, watch, inject } from 'vue'
import ClientPool from '@/api/clientPool.js'
import { REVIVAL_APPLIED } from '@/constants/message.js'
const { Modal } = inject('Feedback')
const props = defineProps({
  show: Boolean,
  clientId: [Number, String]
})
const emits = defineEmits(['update:show'])
const showComputed = computed({
  get: () => props.show,
  set: val => emits('update:show', val)
})
/**
 * 二次开发申请
 */
const fromRef = ref(null)
const revivalButtonLoading = ref(false)
const salesSupporters = ref([])
const revivalRequest = reactive({
  clientID: undefined,
  reason: undefined,
  ssid: undefined
})
const rules = {
  ssid: [
    {
      required: true,
      message: 'Please select sales support',
      trigger: 'blur'
    }
  ],
  reason: [
    {
      required: true,
      message: 'Please input reason',
      trigger: 'blur'
    }
  ]
}
ClientPool.getSalesSupporters().then(({ data }) => {
  salesSupporters.value = data
})
const handleRevival = () => {
  fromRef.value.validate().then(() => {
    revivalButtonLoading.value = true
    revivalRequest.clientID = props.clientId
    ClientPool.applyForRevival(revivalRequest)
      .then(() => {
        Modal.success({
          content: REVIVAL_APPLIED,
          onOk: () => {
            showComputed.value = false
          }
        })
      })
      .finally(() => {
        revivalButtonLoading.value = false
      })
  })
}
/**
 * 每次打开清空表单
 */
watch(
  () => showComputed.value,
  value => {
    if (value) {
      revivalRequest.reason = undefined
      revivalRequest.ssid = undefined
    }
  }
)
</script>

<style scoped></style>
